package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.dao.LogicProdDispatchingDetailDAO;
import com.cssy.xxkj.logic.dao.LogicProductionDispatchingDAO;
import com.cssy.xxkj.logic.dao.LogicProductionDispatchingItemDAO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDetailDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingItemDO;
import com.cssy.xxkj.logic.entity.vo.LogicProductionDispatchingDetailItemVO;
import com.cssy.xxkj.logic.service.ILogicProdDispatchingDetailService;
import com.cssy.xxkj.logic.service.ILogicProductionDispatchingService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
/**
 * 生产派工业务方法
 * @modify hf 
 *
 */
@Service("logicProductionDispatchingService")
public class LogicProductionDispatchingServiceImpl implements ILogicProductionDispatchingService {
	private static final Logger logger = Logger.getLogger(LogicProductionDispatchingServiceImpl.class);
	//派工单DAO
	@Resource(name = "logicProductionDispatchingDAO")
	private LogicProductionDispatchingDAO logicProductionDispatchingDAO;
	//派工单item的DAO
	@Resource(name = "logicProductionDispatchingItemDAO")
	private LogicProductionDispatchingItemDAO  logicProductionDispatchingItemDAO;
	//派工详情单DAO
	@Resource(name="logicProdDispatchingDetailDAO")
	private LogicProdDispatchingDetailDAO logicProdDispatchingDetailDAO;
	//生产派工单详情
	@Resource(name="logicProdDispatchingDetailService")
	private ILogicProdDispatchingDetailService logicProdDispatchingDetailService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionDispatchingDO>  list=logicProductionDispatchingDAO.find(scs);
		rs.setRecordCount(logicProductionDispatchingDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicProductionDispatchingDAO.deleteLogicProductionDispatchingDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicProductionDispatchingDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicProductionDispatchingDAO.updateLogicProductionDispatchingDO(t);
	}

	@Override
	public LogicProductionDispatchingDO save(LogicProductionDispatchingDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicProductionDispatchingDAO.insertLogicProductionDispatchingDO(sodo);
		return sodo;
	}

	@Override
	public LogicProductionDispatchingDO findListById(String id) throws SyBaseException {
		return logicProductionDispatchingDAO.findLogicProductionDispatchingDOByPrimaryKey(id);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicProductionDispatchingDAO.deleteBizRemoved(id);
	}

	@Override
	public List<LogicProductionDispatchingItemDO> findDispatItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd001ProDispatId", id, SearchCondition.OP_EQUAL);
		List<LogicProductionDispatchingItemDO>  list=logicProductionDispatchingItemDAO.find(scs);
		return list;
	}
	
	@Override
	public List<LogicProductionDispatchingItemDO> findItemListByExample(SearchConditions scs)throws SyBaseException{
		if(scs.getOrderBy()==null||scs.getOrderBy().equals("")){
			scs.setOrderBy("(zd029Order+0)");
		}else{
			scs.setOrderBy(scs.getOrderBy()+" , (zd029Order+0)");
		}
		List<LogicProductionDispatchingItemDO>  list = logicProductionDispatchingItemDAO.find(scs);
		return list;
	}
	
	@Override
	public void dispatSave(HttpServletRequest request, LogicProductionDispatchingDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("itemdata");
			String dspingId = curAP.getId();
			LogicProductionDispatchingDO dspingEntity = logicProductionDispatchingDAO.findLogicProductionDispatchingDOByPrimaryKey(dspingId);
			if(dspingEntity==null){
				throw new SyBaseException("待派工单数据发生改变，请重新提交。");
			}
			//保存派工单详细主表
			LogicProductionDispatchingDetailDO detailEntity = this.logicProdDispatchingDetailService.dispatchingDetailSave(dspingEntity, request);
			curAP.setDetailCode(detailEntity.getZd001FormCode());
			//保存派工单明细子表
			List<LogicProductionDispatchingItemDO> dspingItemList = JSONArray.parseArray(itemdata,LogicProductionDispatchingItemDO.class);
			if(null==dspingItemList||dspingItemList.size()==0||dspingItemList.isEmpty()){
				throw new SyBaseException("数据保存失败，没有选中需要保存的数据!!!!!");
			}
			Map<String, LogicProductionDispatchingItemDO> patchItemMap = this.findDispatchingItemToMap(dspingId);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("oriId", dspingId);
			Map<String, BigDecimal> detailHasMap = this.logicProdDispatchingDetailService.findQueryDetailHasToMap(paramMap);
			for(LogicProductionDispatchingItemDO dspingItemEn : dspingItemList){
				if(dspingItemEn==null||StringUtils.isBlank(dspingItemEn.getId())){
					//保存派工item
					dspingItemEn.setId(IDCodeTypeUtil.getId());
					dspingItemEn.setZd001ProDispatId(dspingEntity.getId());
					dspingItemEn.setZd002ProDispatCode(dspingEntity.getZd001FormCode());
					dspingItemEn.setZd003CustomerId(dspingEntity.getZd004CustomerId());
					dspingItemEn.setZd004CustomerCode(dspingEntity.getZd004CustomerCode());
					dspingItemEn.setZd005CustomerName(dspingEntity.getZd004CustomerName());
					String keyStr = dspingId+"_"+dspingItemEn.getZd006MaterialsId()+"_"+dspingItemEn.getZd010MaterialsModel()+"_"
							+dspingItemEn.getZd023MaterialsSize()+"_"+dspingItemEn.getZd026MaterialsColor()+"_"
							+dspingItemEn.getZd027MaterialsQuality()+"_"+dspingItemEn.getZd029Process();
					patchItemMap.put(keyStr, dspingItemEn);//保存状态的更改需要的map
					this.logicProductionDispatchingItemDAO.insertLogicProductionDispatchingItemDO(dspingItemEn);
					//保存派工明细item
					this.logicProdDispatchingDetailService.dispatchingDetailItemSave(detailEntity, dspingItemEn,
							dspingItemEn.getZdTheQuantity()==null?BigDecimal.ZERO:dspingItemEn.getZdTheQuantity());
				}else{
					String keyStr = dspingId+"_"+dspingItemEn.getZd006MaterialsId()+"_"+dspingItemEn.getZd010MaterialsModel()+"_"
							+dspingItemEn.getZd023MaterialsSize()+"_"+dspingItemEn.getZd026MaterialsColor()+"_"
							+dspingItemEn.getZd027MaterialsQuality()+"_"+dspingItemEn.getZd029Process();
						//已派工数量
						BigDecimal hasQuantity = BigDecimal.ZERO;
						//总数量
						BigDecimal sumQuantity = dspingItemEn.getZd015PlanQuantity()==null?BigDecimal.ZERO:dspingItemEn.getZd015PlanQuantity();
						//本次派工数量
						BigDecimal theQuantity = dspingItemEn.getZdTheQuantity()==null?BigDecimal.ZERO:dspingItemEn.getZdTheQuantity();
						//赋值已派工数量
						if(detailHasMap==null||detailHasMap.get(keyStr)==null){
							hasQuantity = theQuantity;
						}else{
							hasQuantity = theQuantity.add(detailHasMap.get(keyStr));
						}
						//剩余数量
						BigDecimal surpQuantity = sumQuantity.subtract(hasQuantity);
						int compUp = BigDecimal.ZERO.compareTo(surpQuantity);
						if(compUp==1){
							throw new SyBaseException("错误：你本次派工数量已大于可派工数量。");
						}
						this.logicProdDispatchingDetailService.dispatchingDetailItemSave(detailEntity, dspingItemEn, theQuantity);
						//更改派工单的已派工数
						dspingItemEn.setZd016ProductionQuantity(hasQuantity);
						patchItemMap.put(keyStr, dspingItemEn);
						this.logicProductionDispatchingItemDAO.updateLogicProductionDispatchingItemDO(dspingItemEn);
				}
				
			}
			//更新预派工单的派工状态
			boolean canUp = true;
			for(LogicProductionDispatchingItemDO patchingItem : patchItemMap.values()){
				if(patchingItem==null||StringUtils.isBlank(patchingItem.getId())){
					continue;
				}
				BigDecimal planQuantity = patchingItem.getZd015PlanQuantity()==null?BigDecimal.ZERO:patchingItem.getZd015PlanQuantity();
				BigDecimal hasdQuantity = patchingItem.getZd016ProductionQuantity()==null?BigDecimal.ZERO:patchingItem.getZd016ProductionQuantity();
				int compUp = BigDecimal.ZERO.compareTo(planQuantity.subtract(hasdQuantity));
				if(compUp==-1){
					canUp = false;
				}
			}
			if(canUp){
				dspingEntity.setZd008Billstatus(BillStatusUtil.PRODISPAT_BILL_STATUS_ZTWO);
			}else{
				dspingEntity.setZd008Billstatus(BillStatusUtil.PRODISPAT_BILL_STATUS_ZONE);
			}
			dspingEntity.setBizVersionMark(dspingEntity.getBizVersion());
			this.logicProductionDispatchingDAO.updateLogicProductionDispatchingDO(dspingEntity);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作生产派工单失败！");
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	/**
	 * 派工单的item组装成Map对象
	 * @param dspingId
	 * @return
	 */
	private Map<String, LogicProductionDispatchingItemDO> findDispatchingItemToMap(String dspingId){
		if(StringUtils.isBlank(dspingId)){
			return null;
		}
		List<LogicProductionDispatchingItemDO> allItemList = this.findQueryDispatchingItemList(dspingId);
		if(allItemList==null||allItemList.isEmpty()||allItemList.size()==0){
			return null;
		}else{
			Map<String, LogicProductionDispatchingItemDO> patchingItemMap = new HashMap<String, LogicProductionDispatchingItemDO>();
			for(LogicProductionDispatchingItemDO dispItem : allItemList){
				if(dispItem==null||StringUtils.isBlank(dispItem.getId())){
					continue;
				}
				String keyStr = dspingId+"_"+dispItem.getZd006MaterialsId()+"_"
					+dispItem.getZd010MaterialsModel()+"_"
					+dispItem.getZd023MaterialsSize()+"_"
					+dispItem.getZd026MaterialsColor()+"_"
					+dispItem.getZd027MaterialsQuality()+"_"
					+dispItem.getZd029Process();
				patchingItemMap.put(keyStr, dispItem);
			}
			
			return patchingItemMap;
		}
	}
	
	private List<LogicProductionDispatchingItemDO> findQueryDispatchingItemList(String dspingId){
		SearchConditions dispScs = new SearchConditions();
		dispScs.setRemovedProperty(null);
		dispScs.addCondition("zd001ProDispatId", dspingId, SearchCondition.OP_EQUAL);
		return logicProductionDispatchingItemDAO.find(dispScs);
	}
	
	@Override
	public SearchResult findDispatchingDetailToSum(SearchConditions scs)
			throws SyBaseException{
		SearchResult sr = new SearchResult();
		List detailList = logicProdDispatchingDetailDAO.findDispatchingDetailToSum(scs);
		sr.setResults(detailList);
		sr.setRecordCount(logicProdDispatchingDetailDAO.countDispatchingDetailToSum(scs));
		return sr;
	}
	
	@Override
	public SearchResult findDispatchingDetailBySCS(
			SearchConditions scs) throws SyBaseException {
		SearchResult sr=new SearchResult();
		List<LogicProductionDispatchingDetailItemVO> list=logicProdDispatchingDetailDAO.findDispatchingDetailBySCS(scs);
		for(LogicProductionDispatchingDetailItemVO li:list){
			//派工数减去以取消数
			 BigDecimal price=li.getZd014Price()==null?new BigDecimal(0):li.getZd014Price();
			 BigDecimal quantity=li.getZd013Quantity()==null? new BigDecimal(0):li.getZd013Quantity();
			 BigDecimal backquantity=li.getZd019ReturnQuantity()==null? new BigDecimal(0):li.getZd019ReturnQuantity();
			 li.setAllprice(price.multiply(quantity.subtract(backquantity)));
			 li.setZdTheQuantity(quantity.subtract(backquantity));
		}
		sr.setResults(list);
		sr.setRecordCount(logicProdDispatchingDetailDAO.findDispatchingDetailCountBySCS(scs));;
		return sr;
	}
	
	@Override
	public SearchResult findCollectDispatchingDetailBySCS(
			SearchConditions scs) throws SyBaseException {
		SearchResult sr=new SearchResult();
		List<LogicProductionDispatchingDetailItemVO> list=logicProdDispatchingDetailDAO.findCollectDispatchingDetailBySCS(scs);
		sr.setResults(list);
		sr.setRecordCount(list.size());;
		return sr;
	}
	
	@Override
	public void deleteBizRemovedBySaleId(String backSaleId)throws SyBaseException{
		SearchConditions patchScs = new SearchConditions();
		patchScs.addCondition("zd002SaleId", backSaleId, SearchCondition.OP_EQUAL);
		List<LogicProductionDispatchingDO> patchingList = logicProductionDispatchingDAO.find(patchScs);
		if(patchingList==null||patchingList.isEmpty()||patchingList.size()==0){
			return;
		}else{
			for(LogicProductionDispatchingDO patching : patchingList){
				if(patching==null||StringUtils.isBlank(patching.getId())){
					continue;
				}
				logicProductionDispatchingDAO.deleteBizRemoved(patching.getId());
			}
		}
	}
}
